
var app = new Vue({
	el: '#app',
	data() {
		return {
			options: {},

			// 患者详情
			patientDetail: {},

			videoHistoryList: [],
			// 就诊历史
			historyList: [],
			// 历史视频
			historyVideo: [],

			form: {
				images: [], // 截屏列表
				threshold: 0, // 阀值
				inspectResult: [], // 影像表现
				result: '', // 诊断结果
				inspect_part: '1', // 检查部位
				isSave: '0', // 保存视频
				isInspect: '1', // AI检测
			},

			// 路径列表
			srcIndex: 1,
			srcLength: 152,

			// 视频加载中
			videoLoading: true,
			// 是否显示流图片
			showFlowImg: true,
			// 切换次数，小于该次数的疾病不计算
			stopAiDisease: 0,
			// 播放路径
			playSrc: '',
			// 暂停图片
			stopSrc: '',
			// 历史播放路径
			historySrc: '',
			// 检查部位
			partList: []
		}
	},
	computed: {
		// 检查部位文本
		inspectPart() {
			let list = this.partList;
			let res = null;
			partFor:for(let i = 0; i < list.length; i++) {
				let aItem = list[i].list;
				for(let j = 0; j < aItem.length; j++) {
					let bItem = aItem[j];
					if(bItem.value == this.form.inspect_part) {
						res = bItem;
						break partFor;
					}
				}
			}
			return res;
		},
	},
	mounted() {

		// 参数
		this.options = Tools.parseURL(location.href).params;

		// 播放路径
		this.playSrc = BASE_API+'/video/?id=' + this.options.id;
		// 设置流是否显示
		this.showFlowImg = this.options.detailId ? false : true;
		// 设置流加载中
		this.videoLoading = this.options.detailId ? false :true;
		
		this.getData();

		// 绑定页面按下enter事件
		window.addEventListener('keyup', (e) => {
			if(e.code == 'Space' && !this.options.detailId) {
				let res = this.doScreen();
				if(res) {
					this.form.images.push(res);
				}
			}
		})
	},
	methods: {
		switchTime: Tools.switchTime,

		// 获取数据
		async getData() {
			// 获取患者信息
			this.getPatient();
			// 获取详情
			this.getDetail();
			
			// 获取检查部位类型
			await this.getCheckPart();
			await Tools.switchTime(30);
			// 查询系统配置信息
			this.getSystemSettings();

			// 设置保存视频，AI检测默认值
			this.changeVideoConfig();
		},

		// 获取患者信息
		getPatient() {
			axios({
				method: 'get',
				url: BASE_API+'/listPatient/',
				params: {
					id: this.options.id
				}
			}).then(res1 => {
				if(!res1.data.result) {
					return;
				}
				let res = JSON.parse(res1.data.data);
				if(!res.length) {
					return;
				}
				let obj = {
					id: res[0].pk,
					...res[0].fields
				}
				// 性别
				obj.gender_text = obj.gender == 1 ? '男' : obj.gender == 2 ? '女' : '未知';
				// 年龄
				if(obj.birthday) {
					obj.age = Tools.getAge(obj.birthday, new Date()) + '岁';
				} else {
					obj.age = '未知';
				}
				this.patientDetail = obj;

				// 视屏列表
    		this.videoHistoryList = res1.data.video_list;

				// 获取就诊记录
				this.getHistory();
			})
		},

		// 获取详情
		getDetail() {
			if(!this.options.detailId) {
				return;
			}
			axios({
				method: 'get',
				url: BASE_API+'/getPatientDiagnosis/',
				params: {
					id: this.options.detailId
				}
			}).then(res => {
				let videoList = (res.data.video || []).map(src => BASE_API+src);
				if(videoList.length && videoList[0].indexOf('-inspect.mp4') == -1) {
					videoList.reverse();
				}
				this.historyVideo = videoList;
				if(this.options.detailId && this.historyVideo.length) {
					this.historySrc = this.historyVideo[0];
					// this.historySrc = 'http://www.jplayer.org/video/m4v/Incredibles_Teaser.m4v';
				}
				this.form.images = res.data.data.map(item => {
					return BASE_API+item;
				})
			})
		},

		// 就诊列表
		getHistory() {
			axios({
				method: 'get',
				url: BASE_API+'/listPatientDiagnosis/',
				params: {
					patientId: this.options.id
				}
			}).then(res => {
				if(!res.data.result) {
					return;
				}
				res = JSON.parse(res.data.data);
				this.historyList = res.map(item => {
					let data = item.fields;
					data.id = item.pk;
					// 判断当前就诊记录是否有视屏
          let hasVideo = false;
          if(this.videoHistoryList[this.options.id][data.id]?.length) {
            hasVideo = true;
          }
          data.hasVideo = hasVideo;
					return data;
				})
				if(this.options.detailId) {
					// 获取当期的阀值和诊断结果
					let nowVisit = this.historyList.find(item => item.id == this.options.detailId);
					// 影像表现
					try {
						this.form.inspectResult = JSON.parse(nowVisit.inspectResult);
					} catch(err) {}
					// 诊断结果
					this.form.result = nowVisit.diagnosisResult;
				}
			})
		},

		// 查询系统配置信息
		getSystemSettings() {
			if(!this.options.id) {
				return;
			}
			axios({
				method: 'get',
				url: BASE_API+'/getSystemSettings/',
				params: {
					id: this.options.id
				}
			}).then(res => {
				if(!res.data.result) {
					return;
				}
				// 格式化数据
				let data = JSON.parse(res.data.data);
				// 阈值
				this.form.threshold = Number(data[0].fields.conf_threshold);
				// 检查部位
				this.form.inspect_part = data[0].fields.inspect_part;
				// 初始化影像检测
				if(!this.options.detailId) {
					this.form.inspectResult = [
						{type: this.inspectPart.label, data: ''}
					]
				}
			})
		},

		// 获取检查部位类型
		async getCheckPart() {
			let res = await axios({method: 'get',url: BASE_API+'/static/model_config.json?t='+new Date().getTime(),})

			let aColor = res.data.color.map(item => `rgb(${item.join(',')})`);
			let arr = res.data.model;
			let rList = [];
			arr.forEach((aItem, aIndex) => {
				let list = [];
				aItem.forEach(bItem => {
					let obj = {
						label: bItem.model_name,
						value: bItem.model_id,
						disabled: bItem.disabled
					}
					if(bItem.model_label) {
						let children = [];
						for(let i in bItem.model_label) {
							let cItem = bItem.model_label[i];
							children.push({
								label: cItem.name,
								color: aColor[cItem.color],
								index: cItem.index
							})
						}
						// 排序
						children = children.sort((prev, next) => {
							return prev.index > next.index ? 1 : -1;
						})
						obj.children = children;
					}
					list.push(obj);
				})
				list.push(list.splice(0, 1)[0]);
				// 判断是否所有都是disabled
				let disabled = list.find(item => !item.disabled) ? false : true;
				rList.push({
					list,
					disabled
				})
			})
			this.partList = rList;
		},

		// AI诊断
		getAIDisease() {
			if(this.options.detailId || !this.showFlowImg) {
				return;
			}
			let startAiDisease = this.stopAiDisease;
			axios({
				method: 'get',
				url: BASE_API+'/getDiseaseLabel/',
				params: {
					id: this.options.id
				}
			}).then(res => {
				// 判断是否关闭ai诊断
				if(startAiDisease < this.stopAiDisease) {
					return;
				}
				// 判断最后一个历史是否为当前的影像表现，如果是就更新AI诊断
				let obj = null;
				if(this.form.inspectResult.length) {
					obj = this.form.inspectResult[this.form.inspectResult.length-1];
				}
				if(obj?.type == this.inspectPart.label) {
					obj.data = res.data.data;
				} else {
					this.form.inspectResult.push({
						type: this.inspectPart.label,
						data: res.data.data
					})
				}
				// 添加截图
				if(res.data.img.length) {
					res.data.img.forEach(base64 => {
						this.form.images.push('data:image/png;base64,'+base64);
					})
				}
				setTimeout(() => {
					if(startAiDisease == this.stopAiDisease) {
						this.getAIDisease();
					}
				}, 1000);
			})
		},

		// 加载完成
		videoLoad() {
			let oBox = this.$refs.videoImgBox;
			let oImg = this.$refs.videoImg;
			let oStopImg = this.$refs.stopImg;
			if(oBox.clientWidth/oBox.clientHeight > oImg.clientWidth/oImg.clientHeight) {
				oImg.style.height = oBox.clientHeight+'px';
				oStopImg.style.height = oBox.clientHeight+'px';
			} else {
				oImg.style.width = oBox.clientWidth+'px';
				oStopImg.style.width = oBox.clientWidth+'px';
			}
			this.videoLoading = false;
			// 获取AI诊断
			this.getAIDisease();
		},

		// 截图
		doScreen() {
			if(this.videoLoading) {
				this.$notify({
					duration: 1000,
          title: '提示',
          message: '视频未加载完成，请稍候',
          type: 'warning'
        });
				return false;
			}
			const videoImg = this.$refs.videoImg;
			const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      const ratio = window.devicePixelRatio // 设备像素比（更正分辨率）
      canvas.width = videoImg.clientWidth * ratio
      canvas.height = videoImg.clientHeight * ratio
      ctx.drawImage(videoImg, 0, 0, canvas.width, canvas.height) //绘制图片
      const base64 = canvas.toDataURL('image/png');
      return base64;
      // this.$notify({
      		// duration: 1000,
     //    title: '提示',
     //    message: '截图成功',
     //    type: 'success'
     //  });
		},

		// 删除
		doDeleteScreen(index) {
			this.$confirm('此操作将删除该截图, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      	this.form.images.splice(index, 1);
      }).catch(() => {});
		},

		// 保存就诊结果
		saveVisitResult() {
			// if(!this.form.result) {
			// 	this.$message.error('请输入就诊结果');
			// 	return;
			// }
			const loading = this.$loading({
        lock: true,
        text: '就诊结果保存中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      let res = this.doScreen();
			if(res) {
				this.stopSrc = res;
			}

			let formData = new FormData();
			this.form.images.forEach(base64 => {
				let file = Tools.base64ToFile(base64, '01.png');
				formData.append('images', file);
			})
			formData.append('patientId', this.options.id);
			formData.append('result', this.form.result);
			formData.append('inspectResult', JSON.stringify(this.form.inspectResult));

			axios({
  			method: 'post',
  			url: BASE_API+'/addPatientDiagnosis/',
  			headers: {
			    'accepts': 'application/json',
    			'Content-Type':'multipart/form-data',
			  },
			  data: formData
  		}).then(res => {
  			if(res.data.result) {
  				this.$notify({
  					duration: 1000,
            type: 'success',
            title: '提示',
            message: '保存成功!'
          });
          setTimeout(() => {
          	let data = JSON.parse(res.data.data);
	          this.showDetail({
	          	id: data[0].pk,
	          	...data[0].fields
	          });
          }, 1000);
  			}
  		}).finally(() => {
  			loading.close();
  		})
		},

		// 保存阀值
		saveSystemSettings() {
			return new Promise((resolve, reject) => {
				// 添加切换次数，过滤老循环
				this.stopAiDisease++;

				let params = {
					conf_threshold: this.form.threshold,
					inspect_part: this.form.inspect_part
				}
				axios({
	  			method: 'post',
	  			url: BASE_API+'/updateSystemSettings/',
	  			headers: {
				    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
				  },
				  data: params
	  		}).then(res => {
	  			if(res.data.result) {
	  				// // 开始ai诊断
	  				// this.getAIDisease();
	  				resolve();
	  			}
	  		})
			})
				
		},

		// 改变AI检测状态
		changeVideoConfig(key) {
			if(this.options.detailId) {
				return;
			}
			let params = {};
			if(!key || key == 'isSave') {
				params.isSave = this.form.isSave;
			}
			if(!key || key == 'isInspect') {
				params.isInspect = this.form.isInspect;
			}
			axios({
  			method: 'post',
  			url: BASE_API+'/updateVideoConfig/',
  			headers: {
			    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
			  },
			  data: params
  		}).then(res => {
  			if(res.data.result) {}
  		})
		},

		// 查看详情
		showDetail(row) {
			let options = {
    		id: row.patientId,
    		name: row.name,
    		detailId: row.id
    	}
    	window.location.href = Tools.joinUrl('./videoRecord.html', options);
		},

		// 保存检查部位
		async changeInspectPart(row) {
			if(this.options.detailId || row.disabled) {
				return;
			}
			this.form.inspect_part = row.value;
			// 初始化影像检测
			this.form.inspectResult.push({
				type: this.inspectPart.label,
				data: ''
			});

			// 更新检查部位
			this.saveSystemSettings().then(async () => {
				// 获取AI诊断
				await Tools.waitTimeout(100);
				this.getAIDisease();

				// // 更新影像图片时间戳
				// // 切换图片地址，将调用videoLoad方法，自动
				// let obj = this.parseURL(this.playSrc);
				// obj.params.time = new Date().getTime();
				// this.playSrc = this.joinUrl(`${obj.protocol}://${obj.host}:${obj.port}${obj.path}?`, obj.params);
			});
		},

		// 解析路由参数
    parseURL(url) {
		    var a =  document.createElement('a');
		    a.href = url;
		    return {
		        source: url,
		        protocol: a.protocol.replace(':',''),
		        host: a.hostname,
		        port: a.port,
		        query: a.search,
		        params: (function(){
		            var ret = {},
		                seg = a.search.replace(/^\?/,'').split('&'),
		                len = seg.length, i = 0, s;
		            for (;i<len;i++) {
		                if (!seg[i]) { continue; }
		                s = seg[i].split('=');
		                ret[s[0]] = s[1];
		            }
		            return ret;
		        })(),
		        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
		        hash: a.hash.replace('#',''),
		        path: a.pathname.replace(/^([^\/])/,'/$1'),
		        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
		        segments: a.pathname.replace(/^\//,'').split('/')
		    };
		},

    // 组装路由参数
		joinUrl(path, query) {
		  let arr = [];
		  for(let key in query) {
		    arr.push(key+'='+query[key]);
		  }
		  if(arr.length) {
		    path+='?'+arr.join('&')
		  }
		  return path;
		},

		// 获取当前显示内容
		getPartLabel(list) {
			let res = list[list.length-1].label;
			for(let i = 0; i < list.length; i++) {
				let item = list[i];
				if(item.value == this.form.inspect_part) {
					res = item.label;
					break;
				}
			}
			if(res.length == 2) {
				res = res[0]+'&nbsp;&nbsp;&nbsp;'+res[1];
			}
			return res;
		},

		// 判断当前是否选中
		getPartType(list) {
			let res = '';
			for(let i = 0; i < list.length; i++) {
				let item = list[i];
				if(item.value == this.form.inspect_part) {
					res = 'primary';
					break;
				}
			}
			return res;
		},

		choicePartLv1(list) {
			let choice = this.getPartType(list) == 'primary' ? true : false;
			if(choice) {
				return false;
			}
			this.changeInspectPart(list[list.length-1]);
		},

		// 切换历史视频
		changeHistorySrc(src) {
			this.historySrc = src;
		},

		// 删除视频
		deleteVideo() {
			this.$confirm('此操作将删除该视频, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      	const loading = this.$loading({
          lock: true,
          text: '删除中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

      	let arr = this.historySrc.split('/');
     		let params = {
     			videoName: arr[arr.length-1]
     		}
     		axios({
	  			method: 'post',
	  			url: BASE_API+'/delVideoFile/',
	  			headers: {
				    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
				  },
				  data: params
	  		}).then(res => {
	  			if(res.data.result) {
	  				let index = this.historyVideo.findIndex(item => item == this.historySrc);
	  				this.historyVideo.splice(index, 1);
	  				this.historySrc = '';
	  				if(this.historyVideo.length) {
	  					this.changeHistorySrc(this.historyVideo[0]);
	  				}
	  				loading.close();
	  			}
	  		})
      }).catch(() => {});
		},

		doScreen_1() {
			// const video = this.$refs.video;
			// const canvas = document.createElement('canvas')
   //    const ctx = canvas.getContext('2d')
   //    const ratio = window.devicePixelRatio // 设备像素比（更正分辨率）
   //    canvas.width = video.videoWidth * ratio
   //    canvas.height = video.videoHeight * ratio
   //    ctx.drawImage(video, 0, 0, canvas.width, canvas.height) //绘制图片
   //    const base64 = canvas.toDataURL('image/png');
   //    this.screenList.push({
   //    	src: base64
   //    })
   //    this.$notify({
   	// duration: 1000,
  //       title: '提示',
  //       message: '截图成功',
  //       type: 'success'
  //     });
		}
	}
})